package jbase.project.system.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import jbase.project.system.exception.SysException;
import jbase.project.system.util.CommonMethod;

public class EndIdentificationBlock {

	private byte[] lastIdentification;
	private byte[] matchBuff;
	private int putCnt;
	private ByteArrayOutputStream out;
	private int lastIdentificationLength;

	private CommonMethod commonMethod = CommonMethod.getInstance();

	public EndIdentificationBlock(byte[] lastIdentification) {
		init(lastIdentification);
	}

	private void init(byte[] lastIdentification) {
		this.lastIdentification = lastIdentification;
		this.lastIdentificationLength = lastIdentification.length;
		this.matchBuff = new byte[lastIdentificationLength];
		this.out = new ByteArrayOutputStream();
		this.putCnt = 0;
	}

	public int length() {
		return this.putCnt;
	}

	public void put(byte current) throws SysException {
		this.putCnt++;
		try {
			out.write(new byte[] { current });
			for (int i = 0; i < this.lastIdentificationLength - 1; i++) {
				this.matchBuff[i] = this.matchBuff[i + 1];
			}
			this.matchBuff[this.lastIdentificationLength - 1] = current;
		} catch (IOException e) {
			e.printStackTrace();
			throw new SysException(e);
		}
	}

	public boolean haveComplete() {
		return putCnt >= lastIdentificationLength && commonMethod.isEqual(matchBuff, lastIdentification);
	}

	public ByteArrayOutputStream getByteArrayOutputStream() {
		return this.out;
	}

	@Override
	public String toString() {
		return new String(this.out.toByteArray());
	}

}
